package com.ruyuan.seckilling.publish.async.listener;

import com.ruyuan.seckilling.common.ChannelKey;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.PagePublishResultMessage;
import com.ruyuan.seckilling.publish.async.event.PulishResultEvent;
import com.ruyuan.seckilling.publish.async.event.RemoveStaticPageEvent;
import com.ruyuan.seckilling.publish.config.BussinessConfig;
import com.ruyuan.starter.async.AsyncContext;
import com.ruyuan.starter.async.BossEventBus;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import com.ruyuan.starter.async.listener.EventListener;
import com.ruyuan.starter.async.thread.ExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(ChannelKey.CHANNEL_PUBLISH_RESULT)
public class PublishResultEventListener implements EventListener<PulishResultEvent> {

    @Autowired
    private BossEventBus bossEventBus;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof PulishResultEvent;
    }

    @Override
    public void onEvent(PulishResultEvent event, AsyncContext eventContext) {
        executorService.execute(ChannelKey.CHANNEL_PUBLISH_RESULT, () -> {
            String message = PagePublishResultMessage.builder()
                    .pageLogId(event.getPageLogId())
                    .success(event.isSuccess())
                    .serverIp(BussinessConfig.getMyIp())
                    .build().toJsonString();
            rocketMQTemplate.syncSend(QueueKey.QUEUE_PUBLISH_PAGE_RESULT, message);
            log.info("第3步，发送页面发布的结果, message={}", message);

            RemoveStaticPageEvent e = new RemoveStaticPageEvent();
            e.setStaticPageId(event.getStaticPageId());
            bossEventBus.publish(ChannelKey.CHANNEL_REMOVE_STATIC_PAGE, e, null);
        });
    }
}
